<?php

// execute the CI bootstrap process
CI_bootstrap();

/** 
 * Bootstrap Doctrine.php, register autoloader specify 
 * configuration attributes and load models. 
 */
DoctrineBootstrap();
require_once APPPATH.'/config/constants.php';

echo 'Instalaci&oacute;n de SISMAPC<br/><br/>';

try {
	echo 'Creaci&oacute;n de las tablas de la base de datos...<br/>';
	Doctrine::createTablesFromModels();
	
	echo 'Tablas del esquema creadas exitosamente<br/><br/>';
	echo 'Modelos cargados:<br/>';
	$models = Doctrine::getLoadedModels();
	foreach($models as $model) {
		echo $model.'<br/>';
	}
	
	// continue the process using the Install controller
	//header('Location: install', TRUE, 302);
	//echo "<h3>SISMAPC Installation process</h3>";
  //$this->createTables();		
  createDocumentTypes();
  createPermissionsAndRoles();
  createUsers();
	
	//echo '<br/>El proceso de instalaci&oacute;n ha terminado exitosamente.<br/>';
} catch(Doctrine_Exception $e) {
	echo '<br/><b>Una excepci&oacute;n ha ocurrido durante el proceso de instalaci&oacute;n!</b><br/>'.$e->getMessage();
}

/**
 * Bootstraps implementation section
 */

function CI_bootstrap() {
	// CI section
	
	/*
	|---------------------------------------------------------------
	| PHP ERROR REPORTING LEVEL
	|---------------------------------------------------------------
	|
	| By default CI runs with error reporting set to ALL.  For security
	| reasons you are encouraged to change this when your site goes live.
	| For more info visit:  http://www.php.net/error_reporting
	|
	*/
		error_reporting(E_ALL);
	
	/*
	|---------------------------------------------------------------
	| SYSTEM FOLDER NAME
	|---------------------------------------------------------------
	|
	| This variable must contain the name of your "system" folder.
	| Include the path if the folder is not in the same  directory
	| as this file.
	|
	| NO TRAILING SLASH!
	|
	*/
		$system_folder = "system";
	
	/*
	|---------------------------------------------------------------
	| APPLICATION FOLDER NAME
	|---------------------------------------------------------------
	|
	| If you want this front controller to use a different "application"
	| folder then the default one you can set its name here. The folder 
	| can also be renamed or relocated anywhere on your server.
	| For more info please see the user guide:
	| http://codeigniter.com/user_guide/general/managing_apps.html
	|
	|
	| NO TRAILING SLASH!
	|
	*/
		$application_folder = "application";
	
	/*
	|===============================================================
	| END OF USER CONFIGURABLE SETTINGS
	|===============================================================
	*/
	
	
	/*
	|---------------------------------------------------------------
	| SET THE SERVER PATH
	|---------------------------------------------------------------
	|
	| Let's attempt to determine the full-server path to the "system"
	| folder in order to reduce the possibility of path problems.
	| Note: We only attempt this if the user hasn't specified a 
	| full server path.
	|
	*/
	if (strpos($system_folder, '/') === FALSE)
	{
		if (function_exists('realpath') AND @realpath(dirname(__FILE__)) !== FALSE)
		{
			$system_folder = realpath(dirname(__FILE__)).'/'.$system_folder;
		}
	}
	else
	{
		// Swap directory separators to Unix style for consistency
		$system_folder = str_replace("\\", "/", $system_folder); 
	}
	
	/*
	|---------------------------------------------------------------
	| DEFINE APPLICATION CONSTANTS
	|---------------------------------------------------------------
	|
	| EXT		- The file extension.  Typically ".php"
	| SELF		- The name of THIS file (typically "index.php")
	| FCPATH	- The full server path to THIS file
	| BASEPATH	- The full server path to the "system" folder
	| APPPATH	- The full server path to the "application" folder
	|
	*/
	define('EXT', '.php');
	define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
	define('FCPATH', str_replace(SELF, '', __FILE__));
	define('BASEPATH', $system_folder.'/');
	
	if (is_dir($application_folder))
	{
		define('APPPATH', $application_folder.'/');
	}
	else
	{
		if ($application_folder == '')
		{
			$application_folder = 'application';
		}
	
		define('APPPATH', BASEPATH.$application_folder.'/');
	}
}

function DoctrineBootstrap() {
	require_once(dirname(__FILE__) . '/application/plugins/doctrine/lib/Doctrine.php'); 
	
	// load database configuration from CodeIgniter
	require_once APPPATH.'/config/database.php';
	
	// this will allow Doctrine to load Model classes automatically
	spl_autoload_register(array('Doctrine', 'autoload'));
	
	// we load our database connections into Doctrine_Manager
	// this loop allows us to use multiple connections later on
	foreach ($db as $connection_name => $db_values) {
	
		// first we must convert to dsn format
		$dsn = $db[$connection_name]['dbdriver'] .
			'://' . $db[$connection_name]['username'] .
			':' . $db[$connection_name]['password'].
			'@' . $db[$connection_name]['hostname'] .
			'/' . $db[$connection_name]['database'];
	
		Doctrine_Manager::connection($dsn,$connection_name);
	}
	
	// CodeIgniter's Model class needs to be loaded
	require_once BASEPATH.'/libraries/Model.php';
	
	// telling Doctrine where our models are located
	Doctrine::loadModels(APPPATH.'/models');
	
	// (OPTIONAL) CONFIGURATION BELOW
	
	// this will allow us to use "mutators"
	Doctrine_Manager::getInstance()->setAttribute(
		Doctrine::ATTR_AUTO_ACCESSOR_OVERRIDE, true);
	
	// this sets all table columns to notnull and unsigned (for ints) by default
	Doctrine_Manager::getInstance()->setAttribute(
		Doctrine::ATTR_DEFAULT_COLUMN_OPTIONS,
		array('notnull' => true, 'unsigned' => true));
	
	// set the default primary key to be named 'id', integer, 4 bytes
	Doctrine_Manager::getInstance()->setAttribute(
		Doctrine::ATTR_DEFAULT_IDENTIFIER_OPTIONS,
		array('name' => 'id', 'type' => 'integer', 'length' => 4));
		
	// fix the time zone to avoid PHP warnings
	if( !date_default_timezone_set('America/New_York') ) {
		echo 'There is an error setting the default time zone!.';
		die();
	}	
}

function createDocumentTypes() {
	echo '<br/>Creaci&oacute;n de DocumentTypes...<br/>';
	
	$documentTypeNames = array(
		DOCUMENTTYPE_THESIS => 'Tesis de Pregrado',	
		DOCUMENTTYPE_MASTER_THESIS => 'Tesis de Maestria',
		DOCUMENTTYPE_PHD_ARTICLE => 'Tesis de Doctorado',
		DOCUMENTTYPE_MAGAZINE_ARTICLE => 'Articulo de Revista',
		DOCUMENTTYPE_BOOK => 'Libro',
		DOCUMENTTYPE_ENCYCLOPEDIA => 'Enciclopedia'
	);

	foreach ( $documentTypeNames as $key => $value ) {
		try {
			$dt = new DocumentType();
	    $dt->documentType = $value;
	    $dt->save();
		} catch(Doctrine_Exception $e) {
			throw $e;
		}	
	}
	echo 'DocumentTypes creados exitosamente!<br/>';
}

function createPermissionsAndRoles() {
	echo '<br/>Creaci&oacute;n de roles y permisos...<br/>';
	try {
		$p1 = new Permission(); 
		$p1->permission = PERM_ADMINISTER_DOCUMENTS;
		$p1->save();
		
		$p2 = new Permission(); 
		$p2->permission = PERM_ADMINISTER_USERS;
		$p2->save();
		
		$p3 = new Permission(); 
		$p3->permission = PERM_ACCESS_DOWNLOAD_DOCUMENTS;
		$p3->save();
		
		$p4 = new Permission(); 
		$p4->permission = PERM_ACCESS_DOCUMENTS;
		$p4->save();
		
		$r1 = new Role();
		$r1->name = ROLE_ADMINISTRATOR;
		$r1->permissions[0] = $p1;
		$r1->permissions[1] = $p2;
		$r1->save();
		
		$r2 = new Role();
		$r2->name = ROLE_ANONYMOUS_USER;
		$r2->permissions[0] = $p4;
		$r2->save();
		
		$r3 = new Role();
		$r3->name = ROLE_AUTHENTICATED_USER;
		$r3->permissions[0] = $p3;
		$r3->save();
		echo 'Roles y permisos creados exitosamente!<br/>';
	} catch(Doctrine_Exception $e) {
		throw $e;
	}
}
	
function createUsers() {
	echo '<br/>Creaci&oacute;n de la cuenta de administraci&oacute;n...<br/>';
	try {
		$rolesTable = Doctrine_Core::getTable('Role');
		$roles = $rolesTable->findAll();
		//$roles = new Doctrine_Collection(Doctrine_Core::getTable('Role'));
		
		$anonymousUser = new User();
		$anonymousUser->username = "";
		$anonymousUser->password = "";
		$anonymousUser->email = "";
		// assign the "usuario anonimo" role
		$anonymousUser->roles[0] = $roles[1];
		$anonymousUser->save();
	
		$user = new User();
		$user->username = "admin";
		$user->password = md5("123");
		$user->email = "guidoc@suss.co.cu";
		// assign the administrador role
		$user->roles[0] = $roles[0];
		
		$user->save();
		echo 'Cuenta creados exitosamente!<br/>';
	} catch(Doctrine_Exception $e) {
		throw $e;
	}
}
